from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from datetime import date

# 初始化SQLAlchemy实例
db = SQLAlchemy()


class DailyRecord(db.Model):
    """
    每日健康记录模型
    存储用户的每日健康数据汇总
    """
    __tablename__ = 'daily_record'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    person_id = db.Column(db.String(50), nullable=False, index=True)
    date = db.Column(db.Date, nullable=False, index=True)
    activity_score = db.Column(db.Float, default=0.0)
    glucose_mean = db.Column(db.Float, default=0.0)
    adl = db.Column(db.Float, default=0.0)  # 日常生活能力评分 (0-1标准化)
    sleep_quality = db.Column(db.Float, default=0.0)  # 睡眠质量 (0-1标准化)
    exercise_freq = db.Column(db.Float, default=0.0)  # 运动频率 (0-1标准化)
    diet_score = db.Column(db.Float, default=0.0)  # 饮食评分 (0-1标准化)
    
    def __repr__(self):
        return f'<DailyRecord {self.person_id} on {self.date}>'
    
    def to_dict(self):
        """
        转换为字典格式
        """
        return {
            'id': self.id,
            'person_id': self.person_id,
            'date': str(self.date),
            'activity_score': self.activity_score,
            'glucose_mean': self.glucose_mean,
            'adl': self.adl,
            'sleep_quality': self.sleep_quality,
            'exercise_freq': self.exercise_freq,
            'diet_score': self.diet_score
        }


class HealthThreshold(db.Model):
    """
    健康指标阈值模型
    存储用户的健康指标阈值配置
    """
    __tablename__ = 'health_threshold'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    person_id = db.Column(db.String(50), nullable=False, unique=True, index=True)  # 每个用户只有一条阈值配置
    glucose_threshold = db.Column(db.Float, default=7.0)  # 血糖阈值，默认7.0
    min_activity_score = db.Column(db.Float, default=30.0)  # 最低活动分数，默认30
    min_adl_score = db.Column(db.Float, default=0.7)  # 最低ADL分数，默认0.7
    min_sleep_quality = db.Column(db.Float, default=0.6)  # 最低睡眠质量，默认0.6
    min_exercise_freq = db.Column(db.Float, default=0.3)  # 最低运动频率，默认0.3（每周至少2次）
    min_diet_score = db.Column(db.Float, default=0.6)  # 最低饮食评分，默认0.6
    
    def __repr__(self):
        return f'<HealthThreshold {self.person_id}>'
    
    def to_dict(self):
        """
        转换为字典格式
        """
        return {
            'id': self.id,
            'person_id': self.person_id,
            'glucose_threshold': self.glucose_threshold,
            'min_activity_score': self.min_activity_score,
            'min_adl_score': self.min_adl_score,
            'min_sleep_quality': self.min_sleep_quality,
            'min_exercise_freq': self.min_exercise_freq,
            'min_diet_score': self.min_diet_score
        }


def create_db(app=None, db_path='sqlite:///health_dashboard.db'):
    """
    初始化数据库
    
    Args:
        app: Flask应用实例，如果为None则创建一个新的应用实例
        db_path: 数据库连接字符串，默认为SQLite数据库
    
    Returns:
        Flask应用实例
    """
    if app is None:
        app = Flask(__name__)
    
    # 配置数据库
    app.config['SQLALCHEMY_DATABASE_URI'] = db_path
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    
    # 绑定app到db实例
    db.init_app(app)
    
    # 创建所有表
    with app.app_context():
        db.create_all()
        print("数据库初始化完成，表已创建")
    
    return app


if __name__ == '__main__':
    # 如果直接运行此脚本，则初始化数据库
    app = create_db()